module Main exposing (..)

import Html exposing (Html, a, button, code, div, h1, li, text, ul)
import Html.Attributes exposing (href)
import Html.Events exposing (onClick)
import Http
import Navigation
import UrlParser as Url exposing ((</>), (<?>), s, int, stringParam, top)
import Login
import MyList



main =
  Navigation.program UrlChange
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }



type alias Model =
  { route : Route
  , login : Login.Model
  , myList : MyList.Model
  }


init : Navigation.Location -> ( Model, Cmd Msg )
init location =
  ( Model Login Login.initModel MyList.initModel
  , Cmd.none
  )


type Route
  = Home
  | Login
  | ListPage


parser : Url.Parser (Route -> a) a
parser =
  Url.oneOf
    [ Url.map Home top
    , Url.map Login (s "login")
    , Url.map ListPage (s "list")
    ]



type Msg
  = UrlChange Navigation.Location
  | LoginMsg Login.Msg
  | MyListMsg MyList.Msg


-- 触发各自的routeChange事件
enterRoute : Route -> Model -> (Model,Cmd Msg)
enterRoute newRoute model =
 let 
  changed = newRoute /= model.route
 in 
  case newRoute of
   Home -> (model,Cmd.none)
   Login -> (model,Cmd.none)
   ListPage -> 
    case changed of
     True ->
      let
       (newMyList,cmd) = MyList.enterRoute model.myList
      in 
       ({model | myList = newMyList},Cmd.map MyListMsg cmd)
     False -> (model,Cmd.none)
   

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    UrlChange location ->
     let
      route = Maybe.withDefault Home (Url.parseHash parser location)
      (newModel,cmd) = enterRoute route model
     in ( {newModel | route = route } , cmd)
    
    LoginMsg subMsg -> 
     let
      (loginModel,cmd) = Login.update subMsg model.login
     in ({model | login = loginModel},Cmd.map LoginMsg cmd)

    MyListMsg subMsg -> 
     let
      (myListModel,cmd) = MyList.update subMsg model.myList
     in ({model | myList = myListModel},Cmd.map MyListMsg cmd)



subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none



view : Model -> Html Msg
view model =
 case model.route of
  Home -> Html.map LoginMsg (Login.view model.login)
  Login -> Html.map LoginMsg (Login.view model.login)
  ListPage -> Html.map MyListMsg (MyList.view model.myList)